import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 收货地址
    addressInfo: null,
    // 购物车列表
    cart: [],
    // 判断用户是否登录成功
    isLogin: false
  }

  computed = {
    isHaveAddress() {
      if (this.addressInfo === null) {
        return true
      }

      return false
    },

    addressStr() {
      if (this.addressInfo === null) {
        return true
      }

      const {
        provinceName,
        cityName,
        countyName,
        detailInfo } = this.addressInfo

      return provinceName + cityName + countyName + detailInfo
    },

    amount() {
      let allTotal = 0

      this.cart.forEach(item => {
        allTotal += item.price * item.count
      })

      return allTotal * 100
    }
  }

  methods = {
    // 获取收货地址
    async chooseAddress() {
      const res = await wepy.chooseAddress().catch(err => err)

      if (res.errMsg !== 'chooseAddress:ok') {
        return
      }

      this.addressInfo = res
      wepy.setStorageSync('address', res)
      this.$apply()
    },

    // 获取用户信息
    async getUserInfo(userInfo) {
      // 获取用户的信息
      if (userInfo.detail.errMsg !== 'getUserInfo:ok') {
        return wepy.baseToast('获取用户信息失败！')
      }
      console.log(userInfo)

      // 获取用户登录凭证
      const loginRes = await wepy.login()
      console.log(loginRes)

      if (loginRes.errMsg !== 'login:ok') {
        return wepy.baseToast('获取用户信息失败！')
      }

      const { encryptedData, iv, rawData, signature } = userInfo.detail
      // 把参数进行拼接
      const loginParams = {
        code: loginRes.code,
        encryptedData,
        iv,
        rawData,
        signature
      }

      const { data: res } = await wepy.post('/users/wxlogin', loginParams)

      if (res.meta.status !== 200) {
        return wepy.baseToast('微信登录失败！')
      }

      wepy.setStorageSync('token', res.message.token)
      this.isLogin = true
      this.$apply()
    },

    // 发起订单支付
    async onSubmit() {
      // 对价格进行判断
      if (this.amount <= 0) {
        return wepy.baseToast('订单金额不能为0！')
      }
      // 对地址做判断
      if (this.addressInfo === null) {
        return wepy.baseToast('请选择收货地址！')
      }

      // 2. 创建订单
      const { data: res } = await wepy.post('/my/orders/create', {
        order_price: '0.01',
        consignee_addr: this.addressStr,
        order_detail: JSON.stringify(this.cart),
        goods: this.cart.map(item => {
          return {
            goods_id: item.id,
            goods_number: item.count,
            goods_price: item.price
          }
        })
      })

      if (res.meta.status !== 200) {
        return wepy.baseToast('订单创建失败！')
      }

      // 获取订单信息
      const orderInfo = res.message

      // 3. 发起预支付
      const { data: orderResult } = await wepy.post('/my/orders/req_unifiedorder', {
        order_number: orderInfo.order_number
      })

      // 生成预支付订单失败
      if (orderResult.meta.status !== 200) {
        return wepy.baseToast('生成预支付订单失败！')
      }

      // 使用 wepy.requestPayment 发起微信支付
      const payResult = await wepy.requestPayment(orderResult.message.pay).catch(err => err)

      if (payResult.errMsg === 'requestPayment:fail cancel') {
        return wepy.baseToast('取消了微信支付')
      }

      // 4.判断是否支付成功
      const { data: payCheckResult } = await wepy.post('/my/orders/chkOrder', {
        order_number: orderInfo.order_number
      })

      if (payCheckResult.meta.status !== 200) {
        return wepy.baseToast('订单支付失败')
      }

      // 5. 提示用户支付成功
      wepy.showToast({
        title: '支付成功！'
      })

      // 6. 跳转到订单列表页面
      wepy.navigateTo({
        url: '/pages/orderlist'
      })
    }
  }

  onLoad() {
    // 在页面加载期间获取收货地址
    this.addressInfo = wepy.getStorageSync('address') || null

    const newCart = this.$parent.globalData.cart.filter(item => item.isCheck)
    this.cart = newCart
  }
}
